<?php

namespace app\admin\controller;

use app\admin\model\Dish as DishModel;
use app\admin\model\DishFlavor as DishFlavorModel;
use app\common\controller\Backend;
use app\common\model\Category as CategoryModel;
use Exception;
use think\Cache;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\File;

/**
 * 菜品
 *
 * @icon fa fa-circle-o
 */
class Dish extends Backend
{

    /**
     * Dish模型对象
     * @var \app\admin\model\Dish
     */
    protected $model = null;


    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Dish;
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    /**
     * 清除缓存数据
     */
    private function cleanCache($pattern)
    {
        $redis = Cache::store('redis')->handler();
        $keys = $redis->keys($pattern);
        if (!empty($keys)) {
            $redis->del($keys);
        }
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            // print_r($where);
            $list = $this->model
                ->with(['category'])
                ->where($where)
                ->order($sort, $order)
                ->paginate($limit);
            // print_r($list);
            foreach ($list as $row) {

                $row->getRelation('category')->visible(['name']);
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        // 请求参数
        $params = $this->request->post('row/a');
        // dump($params);
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }

        // 权限验证
        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }

        // 菜品数据
        // 第一步：检查文件是否存在
        $imagePath = ROOT_PATH . 'public' . str_replace('/', DS, $params['image']);
        if (!is_file($imagePath)) {
            // 记录日志（可选，但推荐）
            \think\Log::write("图片不存在，路径：{$imagePath}", 'error');
            return json([
                'code' => 0,
                'msg'  => '图片不存在，请重新上传'
            ]);
        }
        $image = new File($imagePath);
        $data = [
            'name' => $params['name'] ?? '',
            'category' => $params['category_id'] ?? '',
            'price' => $params['price'] ?? '',
            'image' => $image,
            'description' => $params['description'] ?? '',
        ];

        // 验证数据
        $validate = validate('Dish');
        if (!$validate->scene('add')->check($data)) {
            $this->error($validate->getError());
        }

        // 验证菜品名称是否重复
        $dish = $this->model->where('name', $params['name'])->find();
        if ($dish) {
            $this->error('菜品名称重复，请调整');
        }

        $result = false;
        Db::startTrans();
        try {
            $adminId = $this->auth->__get('id');
            // 添加菜品
            $dish = $this->model;
            $dish->name = $params['name'];
            $dish->category_id = $params['category_id'];
            $dish->price = $params['price'];
            $dish->image = $params['image'];
            $dish->description = $params['description'];
            $dish->create_user = $adminId;
            $dish->update_user = $adminId;
            $dish->save();

            // 添加口味
            $flavors = [];
            if (!empty($params['dish_flavor'])) {
                // 获取菜品自增id
                // $dishId = $dish->id;
                // 实例化菜品模型
                $dishFlavor = new DishFlavorModel;
                // 处理口味数据
                foreach ($params['dish_flavor'] as $k => $flavor) {
                    // 口味名称
                    $name = $dishFlavor->getDishFlavorTypeKeyList()[$flavor['key']];
                    // 口味名称对应的标签值
                    $values =  $dishFlavor->getDishFlavorTypeList()[$name];
                    // 标签值转化为数组
                    $valuesArr = explode(",", $values);
                    // 当前口味对象对应的标签值
                    $flavorVal = $flavor['val'][1];
                    // 当前口味对象的标签值转化为数组
                    $flavorValArr = explode(",", $flavorVal);
                    // 口味标签字符串
                    $valueStr = json_encode(
                        array_map(function ($idx) use ($valuesArr) {
                            return $valuesArr[$idx];
                        }, $flavorValArr),
                        JSON_UNESCAPED_UNICODE
                    );
                    $flavors[] = [
                        // 'dish_id' => $dishId,
                        'name' => $name,
                        'value' => $valueStr,
                    ];
                }
                // $dishFlavorRet = $dishFlavor->saveAll($flavors);
                // 关联新增菜品口味
                $dish->flavors()->saveAll($flavors);
            }

            $categoryId = $dish->category_id;
            $key = 'dish_' . $categoryId;
            $this->cleanCache($key);

            $result = true;
            Db::commit();
        } catch (ValidateException | PDOException | Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($result === false) {
            $this->error(__('No rows were inserted'));
        }
        $this->success();
    }

    /**
     * 编辑
     *
     * @param $ids
     * @return string
     * @throws DbException
     * @throws \think\Exception
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds) && !in_array($row[$this->dataLimitField], $adminIds)) {
            $this->error(__('You have no permission'));
        }

        if (false === $this->request->isPost()) {
            // 口味数组初始化
            $flavorList = [];
            $dish = DishModel::get($ids);
            $flavors = $dish->flavors;

            if ($flavors) {
                $dishFlavor = new DishFlavorModel();
                $dishFlavorTypeKeyList = $dishFlavor->getDishFlavorTypeKeyList();

                foreach ($flavors as $flavor) {
                    $nameIndex = array_search($flavor->name, $dishFlavorTypeKeyList);
                    $valueArr = json_decode($flavor->value, true);
                    $valueIndexs = implode(',', array_keys($valueArr)); // 转换为标签索引字符串

                    $flavorList[] = [
                        'id' => $flavor->id,
                        'name' => $flavor->name,
                        'nameIndex' => $nameIndex,
                        'value' => $valueArr,
                        'valueIndexs' => $valueIndexs,
                    ];
                }
            }

            $this->view->assign('flavorList', $flavorList);
            $this->view->assign('row', $row);
            return $this->view->fetch();
        }

        // 请求参数
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', 'row'));
        }
        // 权限验证
        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }

        // 菜品数据
        // 第一步：检查文件是否存在
        $imagePath = ROOT_PATH . 'public' . str_replace('/', DS, $params['image']);
        if (!is_file($imagePath)) {
            // 记录日志（可选，但推荐）
            \think\Log::write("图片不存在，路径：{$imagePath}", 'error');
            return json([
                'code' => 0,
                'msg'  => '图片不存在，请重新上传'
            ]);
        }
        $data = [
            'name' => $params['name'] ?? '',
            'category' => $params['category_id'] ?? '',
            'price' => $params['price'] ?? '',
            'image' => $image,
            'description' => $params['description'] ?? '',
            'status' => $params['status'] ?? '',
        ];

        // 验证数据合法性
        $validate = validate('Dish');
        if (!$validate->scene('edit')->check($data)) {
            $this->error($validate->getError());
        }

        // 验证菜品名称是否重复
        $dish = $this->model
            ->where('id', '<>', $ids)
            ->where('name', $params['name'])
            ->find();

        if ($dish) {
            $this->error('菜品名称重复，请调整');
        }

        $result = false;
        Db::startTrans();
        try {
            // 模型验证
            if ($this->modelValidate) {
                $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                $validate = is_bool($this->modelValidate)
                    ? ($this->modelSceneValidate ? $name . '.edit' : $name)
                    : $this->modelValidate;
                $this->model->validateFailException()->validate($validate);
            }
            $adminId = $this->auth->__get('id');
            // 更新菜品基础信息
            $dish = DishModel::get($ids);
            $dish->save([
                'name' => $params['name'],
                'category_id' => $params['category_id'],
                'price' => $params['price'],
                'image' => $params['image'],
                'description' => $params['description'],
                'status' => $params['status'],
                'update_user' =>  $adminId,
            ]);

            // 处理口味数据：先删除原有口味
            $dishFlavorModel = new DishFlavorModel();
            $dishFlavorModel->where('dish_id', $ids)->delete();

            // 新增口味数据
            if (!empty($params['dish_flavor'])) {
                $baseFlavor = new DishFlavorModel();

                $newFlavors = [];
                // 处理口味数据
                foreach ($params['dish_flavor'] as $k => $flavor) {
                    // 口味名称
                    $name = $baseFlavor->getDishFlavorTypeKeyList()[$flavor['key']];
                    // 口味名称对应的标签值
                    $values =  $baseFlavor->getDishFlavorTypeList()[$name];
                    // 标签值转化为数组
                    $valuesArr = explode(",", $values);
                    // 当前口味对象对应的标签值
                    $flavorVal = $flavor['val'][1];
                    // 当前口味对象的标签值转化为数组
                    $flavorValArr = explode(",", $flavorVal);
                    // 口味标签字符串
                    $valueStr = json_encode(
                        array_map(function ($idx) use ($valuesArr) {
                            return $valuesArr[$idx];
                        }, $flavorValArr),
                        JSON_UNESCAPED_UNICODE
                    );
                    $newFlavors[] = [
                        'dish_id' => $ids,
                        'name' => $name,
                        'value' => $valueStr,
                    ];
                }

                if (!empty($newFlavors)) {
                    $dishFlavorModel->saveAll($newFlavors);
                }
            }
            // 删除所有菜品的缓存数据
            $this->cleanCache('dish_*');
            $result = true;
            Db::commit();
        } catch (ValidateException | PDOException | Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

        if (!$result) {
            $this->error(__('Operation failed'));
        }
        $this->success();
    }

    /**
     * 删除
     *
     * @param $ids
     * @return void
     * @throws DbException
     * @throws DataNotFoundException
     * @throws ModelNotFoundException
     */
    public function del($ids = null)
    {
        if (false === $this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ?: $this->request->post("ids");
        if (empty($ids)) {
            $this->error(__('Parameter %s can not be empty', 'ids'));
        }
        $pk = $this->model->getPk();
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = $this->model->where($pk, 'in', $ids)->select();

        $count = 0;
        Db::startTrans();
        try {
            foreach ($list as $item) {
                // 起售状态下不可删除
                if ($item->status == 1) {
                    throw new Exception('在售状态下，不可删除菜品');
                }
                $category = CategoryModel::get($item->category_id);
                if ($category->type == 2) {
                    throw new Exception('被套餐关联的菜品不能删除');
                }
                // 删除菜品对应口味
                $item->flavors()->delete();
                $count += $item->delete();
            }
            // 删除所有菜品的缓存数据
            $this->cleanCache('dish_*');
            Db::commit();
        } catch (PDOException | Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if ($count) {
            $this->success();
        }
        $this->error(__('No rows were deleted'));
    }
}
